package com.fingard.dsp.bank.directbank.cgb02;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IContract;
import com.fingard.dsp.bank.reqrespobj.contract.*;
import com.fingard.dsp.bank.reqrespobj.contract.detail.RetAtsContractDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Date;

/**
 * 广发银行签约
 * 
 * 参考文档：广发银行银企直联接口说明文档-易收款1.5.doc
 * 
 * @author Cruise
 * @date 2019/4/28
 */
public class CGB02Contract extends CGB02Base implements IContract {
	/**
	 * 开发接口：
	 * 3.1.1.1	代扣签约（2034）XML格式
	 * 3.1.1.3	代扣签约验证（2036）XML格式
	 */
	@Override
	public RetAtsContract contract(ReqContract p_req) throws Exception {
		RetAtsContract retAts = new RetAtsContract(p_req.reqHeader);
		RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
		tmpRetDetail.reqSeqID = p_req.contractDetail.askNumber;
		
		try {
			XmlTextWriter xmlWriter = new XmlTextWriter();
			xmlWriter.autoFormat = false;
			
			if ("01".equals(p_req.contractDetail.step)) {
				CGB02Header bankHeader = new CGB02Header();
				bankHeader.reqSeqID = p_req.contractDetail.askNumber;
				bankHeader.transCode = "2034";
				
				writeCommonHeader(xmlWriter, bankHeader);
				
				xmlWriter.writeStartElement("Body");
				xmlWriter.writeElementString("signNo", p_req.contractDetail.askNumber);
				xmlWriter.writeElementString("protocolNo", p_req.contractDetail.sourceNoteCode);
				xmlWriter.writeElementString("intAcc", p_req.contractDetail.recAct);
				xmlWriter.writeElementString("signType", "1");
				xmlWriter.writeElementString("outAcc", p_req.contractDetail.payAct);
				xmlWriter.writeElementString("outAccName", p_req.contractDetail.payName);
				xmlWriter.writeElementString("idType", convertCertTypeToBank(p_req.contractDetail.certType));
				xmlWriter.writeElementString("idNo", p_req.contractDetail.certNum);
				xmlWriter.writeElementString("contactTel", p_req.contractDetail.cellPhone);
				
				String singleLimit = p_req.contractDetail.singleLimit;
				if (StringHelper.isNullOrEmpty(singleLimit)) {
					if (getBankConfig().getValueAsBool("singleLimitCut")) {
						singleLimit = getBankConfig().getMapValueByKey("singleLimitMapping", p_req.contractDetail.payBankCode);
					} else {
						singleLimit = getBankConfig().getMapValueByKey("contractKeyMapping", "singleLimit");
					}
					
					if (StringHelper.isNullOrEmpty(singleLimit)) {
						tmpRetDetail.respCode = "-1";
						tmpRetDetail.respInfo = "缺失配置节点'singleLimit'或值为空!";
						retAts.writeRetDetail(tmpRetDetail);
						return retAts;
					}
				}
				xmlWriter.writeElementString("ctrAmt", singleLimit);
				
				String dayAmtLimit = p_req.contractDetail.dayAmtLimit;
				if (StringHelper.isNullOrEmpty(dayAmtLimit)) {
					dayAmtLimit = getBankConfig().getMapValueByKey("contractKeyMapping", "dayAmtLimit");
					if (StringHelper.isNullOrEmpty(dayAmtLimit)) {
						tmpRetDetail.respCode = "-1";
						tmpRetDetail.respInfo = "缺失配置节点'dayAmtLimit'或值为空!";
						retAts.writeRetDetail(tmpRetDetail);
						return retAts;
					}
				}
				xmlWriter.writeElementString("dayCtrAmt", dayAmtLimit);
				xmlWriter.writeElementString("bussType", "006");
				xmlWriter.writeElementString("beginDate", Format.Date8Format.format(new Date()));
				
				String deadLine = p_req.contractDetail.deadLine;
				if (StringHelper.isNullOrEmpty(deadLine)) {
					deadLine = getBankConfig().getMapValueByKey("contractKeyMapping", "deadLine");
					if (StringHelper.isNullOrEmpty(deadLine)) {
						tmpRetDetail.respCode = "-1";
						tmpRetDetail.respInfo = "缺失配置节点'deadLine'或值为空!";
						retAts.writeRetDetail(tmpRetDetail);
						return retAts;
					}
				}
				xmlWriter.writeElementString("endDate", deadLine);
				xmlWriter.writeElementString("reserve1", "");
				xmlWriter.writeElementString("reserve2", "");
				xmlWriter.writeElementString("reserve3", "");
				xmlWriter.writeEndDocument();
			} else if ("02".equals(p_req.contractDetail.step)) {
				CGB02Header bankHeader = new CGB02Header();
				bankHeader.reqSeqID = p_req.contractDetail.askNumber;
				bankHeader.transCode = "2036";
				
				writeCommonHeader(xmlWriter, bankHeader);
				
				xmlWriter.writeStartElement("Body");
				xmlWriter.writeElementString("signNo", p_req.contractDetail.askNumber);
				xmlWriter.writeElementString("protocolNo", p_req.contractDetail.sourceNoteCode);
				xmlWriter.writeElementString("intAcc", p_req.contractDetail.recAct);
				xmlWriter.writeElementString("signType", "1");
				xmlWriter.writeElementString("outAcc", p_req.contractDetail.payAct);
				xmlWriter.writeElementString("outAccName", p_req.contractDetail.payName);
				xmlWriter.writeElementString("idType", convertCertTypeToBank(p_req.contractDetail.certType));
				xmlWriter.writeElementString("idNo", p_req.contractDetail.certNum);
				xmlWriter.writeElementString("contactTel", p_req.contractDetail.cellPhone);
				
				String singleLimit = p_req.contractDetail.singleLimit;
				if (StringHelper.isNullOrEmpty(singleLimit) || "0".equals(singleLimit)) {
					if (getBankConfig().getValueAsBool("singleLimitCut")) {
						singleLimit = getBankConfig().getMapValueByKey("singleLimitMapping", p_req.contractDetail.payBankCode);
					} else {
						singleLimit = getBankConfig().getMapValueByKey("contractKeyMapping", "singleLimit");
					}
					
					if (StringHelper.isNullOrEmpty(singleLimit)) {
						tmpRetDetail.respCode = "-1";
						tmpRetDetail.respInfo = "缺失配置节点'singleLimit'或值为空!";
						retAts.writeRetDetail(tmpRetDetail);
						return retAts;
					}
				}
				xmlWriter.writeElementString("ctrAmt", singleLimit);
				
				String dayAmtLimit = p_req.contractDetail.dayAmtLimit;
				if (StringHelper.isNullOrEmpty(dayAmtLimit)) {
					dayAmtLimit = getBankConfig().getMapValueByKey("contractKeyMapping", "dayAmtLimit");
					if (StringHelper.isNullOrEmpty(dayAmtLimit)) {
						tmpRetDetail.respCode = "-1";
						tmpRetDetail.respInfo = "缺失配置节点'dayAmtLimit'或值为空!";
						retAts.writeRetDetail(tmpRetDetail);
						return retAts;
					}
				}
				xmlWriter.writeElementString("dayCtrAmt", dayAmtLimit);
				xmlWriter.writeElementString("bussType", "006");
				xmlWriter.writeElementString("beginDate", Format.Date8Format.format(new Date()));
				
				String deadLine = p_req.contractDetail.deadLine;
				if (StringHelper.isNullOrEmpty(deadLine)) {
					deadLine = getBankConfig().getMapValueByKey("contractKeyMapping", "deadLine");
					if (StringHelper.isNullOrEmpty(deadLine)) {
						tmpRetDetail.respCode = "-1";
						tmpRetDetail.respInfo = "缺失配置节点'deadLine'或值为空!";
						retAts.writeRetDetail(tmpRetDetail);
						return retAts;
					}
				}
				xmlWriter.writeElementString("endDate", deadLine);
				xmlWriter.writeElementString("bankSignDate", p_req.contractDetail.smsCode);
				xmlWriter.writeElementString("reserve1", "");
				xmlWriter.writeElementString("reserve2", "");
				xmlWriter.writeElementString("reserve3", "");
				xmlWriter.writeEndDocument();
			} else {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = "未能识别的step：" + p_req.contractDetail.step;
				retAts.writeRetDetail(tmpRetDetail);
				return retAts;
			}
			
			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
			
			if(tmpStrRet[0].length() == 0) {
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
				if (tmpBkReader != null) {
					tmpRetDetail.respCode = "0";
					
					String tmpRespCode = tmpBkReader.getFirstText("/BEDC/Message/commHead/retCode");
					if ("000".equals(tmpRespCode)) {
						String transStatus = tmpBkReader.getFirstText("/BEDC/Message/Body/tranStatus");
						if("01".equals(p_req.contractDetail.step)) {
							tmpRetDetail.respInfo = StringHelper.joinNotEmpty("_", tmpRespCode, tmpBkReader.getFirstText("/BEDC/Message/Body/errMsg"));
							if (!"1".equals(transStatus)) {
								tmpRetDetail.respCode = "-1";
								tmpRetDetail.respInfo = StringHelper.joinNotEmpty("_", transStatus, tmpBkReader.getFirstText("/BEDC/Message/Body/errMsg"));
							}
							tmpRetDetail.signConfirmType = "2";
						} else {
							if ("1".equals(transStatus)) {
								tmpRetDetail.signState = ContractState.SUCCESS;
							} else {
								tmpRetDetail.signState = ContractState.FAIL;
							}
							tmpRetDetail.authCode = tmpBkReader.getFirstText("/BEDC/Message/Body/signBankNo");
							String transInfo = tmpBkReader.getFirstText("/BEDC/Message/Body/errMsg");
							if (StringHelper.hasAnyChar(transInfo)) {
								tmpRetDetail.respInfo = transInfo;
							}
						}
					} else {
						tmpRetDetail.respCode = "0";
						tmpRetDetail.respInfo = tmpRespCode;
					}
                    tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", tmpRespCode);
				} else {
					tmpRetDetail.respCode = "-1";
					tmpRetDetail.respInfo = tmpSbMsg.toString();
				}
			} else {
				tmpRetDetail.respCode = "-1"; 
				tmpRetDetail.respInfo = tmpStrRet[1];
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

    @Override
    public RetAtsContract upContract(ReqContract p_req) throws Exception {
        return null;
    }

    /**
	 * 开发接口：
	 * 3.1.1.4	代扣签约/解约结果查询（2037）XML格式
	 */
	@Override
	public RetAtsContract qryContract(ReqContract p_reqQry) throws Exception {
		RetAtsContract retAts = new RetAtsContract(p_reqQry.reqHeader);
		RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
		tmpRetDetail.reqSeqID = p_reqQry.contractDetail.askNumber;
		
		try {
			CGB02Header bankHeader = new CGB02Header();
			bankHeader.reqSeqID = p_reqQry.contractDetail.askNumber;
			bankHeader.transCode = "2037";
			
			XmlTextWriter xmlWriter = new XmlTextWriter();
			xmlWriter.autoFormat = false;
			writeCommonHeader(xmlWriter, bankHeader);
			
			xmlWriter.writeStartElement("Body");
			xmlWriter.writeElementString("signNo", p_reqQry.contractDetail.askNumber);
			xmlWriter.writeElementString("reserve1", "");
			xmlWriter.writeElementString("reserve2", "");
			xmlWriter.writeEndDocument();
			
			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
			
			if(tmpStrRet[0].length() == 0) {
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
				if (tmpBkReader != null) {
					tmpRetDetail.respCode = "0";
					
					String tmpRespCode = tmpBkReader.getFirstText("/BEDC/Message/commHead/retCode");
					if ("000".equals(tmpRespCode)) {
						//0：处理中						1：成功						2：失败						3：无记录
						String transStatus = tmpBkReader.getFirstText("/BEDC/Message/Body/tranStatus");
						if ("1".equals(transStatus)) {
							tmpRetDetail.signState = ContractState.SUCCESS;
						} else if ("2".equals(transStatus)) {
							tmpRetDetail.signState = ContractState.FAIL;
						} else {
							tmpRetDetail.signState = ContractState.SIGNING;
						}
						tmpRetDetail.authCode = tmpBkReader.getFirstText("/BEDC/Message/Body/signBankNo");
						String transInfo = tmpBkReader.getFirstText("/BEDC/Message/Body/errMsg");
						if (StringHelper.hasAnyChar(transInfo)) {
							tmpRetDetail.respInfo = transInfo;
						}
					} else {
						tmpRetDetail.respCode = "-1";
						tmpRetDetail.respInfo = tmpRespCode;
					}
				} else {
					tmpRetDetail.respCode = "-1";
					tmpRetDetail.respInfo = tmpSbMsg.toString();
				}
			} else {
				tmpRetDetail.respCode = "-1"; 
				tmpRetDetail.respInfo = tmpStrRet[1];
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

    @Override
    public RetAtsQryBatContract qryBatContract(ReqQryBatContract p_reqQry) throws Exception {
        return null;
    }
}
